/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package consumo.face.cadastro.converter;

import consumo.entity.Concessionaria;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author Carlos Taschetto
 */
@FacesConverter(value="conceConverter")  
public class ConceConverter implements Converter {
    
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value != null) {  
            return this.getAttributesFrom(component).get(value);  
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null  
                && !"".equals(value)) {  
  
            Concessionaria entity = (Concessionaria) value;  
  
            // adiciona item como atributo do componente  
            this.addAttribute(component, entity);  
  
            Integer codigo = entity.getId();  
            if (codigo != null) {  
                return String.valueOf(codigo);  
            }  
        }  
  
        return (String) value;
    }
    
    protected void addAttribute(UIComponent component, Concessionaria o) {  
        String key = o.getId().toString(); // codigo da empresa como chave neste caso  
        this.getAttributesFrom(component).put(key, o);  
    }  
    
    protected Map<String, Object> getAttributesFrom(UIComponent component) {  
        System.out.println(component.getAttributes());
        return component.getAttributes();  
    }
}
